package com.photoeditor.demo.ui.dialog;


import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.bean.stash.IGifBean;
import com.photoeditor.demo.model.bean.stash.RecentlyGifBean;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.util.APKAssertImageLoader;
import com.rey.material.widget.ProgressView;
import com.zhy.magicviewpager.transformer.ScaleInTransformer;

import java.util.ArrayList;
import java.util.List;

import me.xiaopan.sketch.SketchImageView;
import me.xiaopan.sketch.drawable.ImageAttrs;
import me.xiaopan.sketch.request.CancelCause;
import me.xiaopan.sketch.request.DisplayListener;
import me.xiaopan.sketch.request.ErrorCause;
import me.xiaopan.sketch.request.ImageFrom;

/**
 *
 *
 * 类描述:<br>弹出来的gif图和facebook广告banner图的泡泡窗口
 * 一定要设置一个background不然点击外面或者返回键不会消失
 *
 */
public class MainPagePopGifPopup extends PopupWindow {


	private Context mContext;
	private List<IGifBean> mGifIdList = new ArrayList<>();
	private ViewPager mViewPager;
	private MainPageAdapter mMainPageAdapter;
	private RelativeLayout mAdViewBannerContainer;
	private ImageView mCloseBtn;
	private View mApplyBtn;
	private ProgressBar mProgressBar;
	private TextView mApplyTv;
	private boolean mIsLocal;
//	private AllinoneAdView mAdView;
	private View mAdView;
//	private String mAdCacheKey;
	private boolean mAdShowing = false;
	private boolean mDynamicSize;
	private static final int defaultSize = DeviceUtils.dip2px(ComponentContext.getContext(), 156);
	private static final int gifPagerMargin = DeviceUtils.dip2px(ComponentContext.getContext(), 42);
	private static final int gifMaxWidth = ImageHelper.SCREEN_WIDTH - gifPagerMargin*2
			 - ComponentContext.getContext().getResources().getDimensionPixelSize(R.dimen.sticker_detail_page_layout_left_right_margin)*2;

	private boolean mLoadAssert;
	private Resources mResources;
	private String mRootUrl;

	public MainPagePopGifPopup(Context context, List<String> urls, int position, boolean loadAssert, String pkgName, String rootUrl) {
		this(context, createList(urls), position, false, loadAssert, pkgName, rootUrl);
	}

	private static List<IGifBean> createList(List<String> urls) {
		List<IGifBean> list = new ArrayList<>();
		int[] dims = {defaultSize, defaultSize};
		for(String url : urls) {
			list.add(new RecentlyGifBean(url, dims));
		}
		return list;
	}
	public MainPagePopGifPopup(Context context, List<? extends IGifBean> gifIdList,
                               final int position, boolean dynamicSize) {
		this(context, gifIdList, position, dynamicSize, false, "", "");
	}

	public MainPagePopGifPopup(Context context, List<? extends IGifBean> gifIdList,
                               final int position, boolean dynamicSize, boolean loadAssert, String pkgName, String rootUrl) {
		mLoadAssert = loadAssert;
		if(mLoadAssert) {
			mRootUrl = StoreOnlineBean.removeQueryString(rootUrl);
			try {
				mResources = ComponentContext.getContext().createPackageContext(pkgName, Context.CONTEXT_IGNORE_SECURITY).getResources();
			} catch (PackageManager.NameNotFoundException e) {
				e.printStackTrace();
			}
		}
		mContext = context;
		mGifIdList.addAll(gifIdList);
//		mAdCacheKey = adCacheKey;
		this.mDynamicSize = dynamicSize;
		View view = LayoutInflater.from(mContext).inflate(R.layout.mainpage_pop_gif, null);
		mAdViewBannerContainer = (RelativeLayout) view.findViewById(R.id.ad_view_layout);
		mCloseBtn = (ImageView) view.findViewById(R.id.iv_close);
		this.setContentView(view);
		this.setWidth(LayoutParams.MATCH_PARENT);
		this.setHeight(LayoutParams.MATCH_PARENT);
		// 设置弹窗可点击
		this.setFocusable(true);
//		this.setOutsideTouchable(true);
		// 实例化一个ColorDrawable颜色为半透明
		ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
		//点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
		this.setBackgroundDrawable(dw);

		RelativeLayout pagerLayout = (RelativeLayout) view.findViewById(R.id.page_layout);
		pagerLayout.setOnTouchListener(new View.OnTouchListener() {//由于设置了Margin  无法滑动父View的区域  所以这里将父View的事件转给了他
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				//点击事件超出viewpager范围
				boolean a = false;
				try {
					a = mViewPager.onTouchEvent(event);
				}catch (Exception e) {
					a = false;
				}
				return a;
			}
		});

		mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
		mViewPager.setPageMargin(context.getResources().getDimensionPixelSize(R.dimen.sticker_detail_page_margin));
		mViewPager.setPageTransformer(true, new ScaleInTransformer(140f/156));
		mViewPager.setOffscreenPageLimit(3);
		if(mDynamicSize) {
			RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
			lp.leftMargin = gifPagerMargin;
			lp.rightMargin = lp.leftMargin;
			mViewPager.setLayoutParams(lp);
		} else {
			RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
			int layoutLeftRightMargin = context.getResources().getDimensionPixelSize(R.dimen.sticker_detail_page_layout_left_right_margin);
			lp.leftMargin = (ImageHelper.SCREEN_WIDTH
					- layoutLeftRightMargin * 2
					- DeviceUtils.dip2px(context, 156)) / 2;
			lp.rightMargin = lp.leftMargin;
			mViewPager.setLayoutParams(lp);
		}

		mMainPageAdapter = new MainPageAdapter(mContext, mGifIdList);
		mViewPager.setAdapter(mMainPageAdapter);
		mViewPager.setCurrentItem(position, true);

		mApplyTv = view.findViewById(R.id.store_download);
		mProgressBar = view.findViewById(R.id.store_progressBar);
		mApplyBtn = view.findViewById(R.id.store_download_layout);
		mApplyBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mOnApplyBtnClickListener != null) {
					mOnApplyBtnClickListener.onApplyBtnClick(mViewPager.getCurrentItem());
				}
			}
		});
		setAnimationStyle(R.style.stickerDetailStyle);
//		view.findViewById(R.id.content).setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				dismiss();
//			}
//		});

		mCloseBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismiss();
			}
		});

	}

	public void setApplyBtnVisibility(int visibility) {
		mApplyBtn.setVisibility(visibility);
	}

	public void setApplyBtnEnable() {

	}

	public void setProgress(int progress) {
		mProgressBar.setProgress(progress);
	}

	public void setDownText(int resId, int bgResId, int color) {
		mApplyTv.setText(resId);
		mApplyTv.setTextColor(color);
		mApplyBtn.setBackgroundResource(bgResId);
		mApplyTv.setCompoundDrawables(null, null, null, null);
	}

	public void setDownText(String res, int bgResId, int color) {
		mApplyTv.setText(res);
		mApplyTv.setTextColor(color);
		mApplyBtn.setBackgroundResource(bgResId);
		mApplyTv.setCompoundDrawables(null, null, null, null);
	}

	public void setDownText(String res, int bgResId, int color, int leftDrawableId) {
		setDownText(res, bgResId, color);
		Drawable drawable = ComponentContext.getContext().getResources().getDrawable(leftDrawableId);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
		mApplyTv.setCompoundDrawables(drawable, null, null, null);
		mApplyTv.setCompoundDrawablePadding(DeviceUtils.dip2px(ComponentContext.getContext(), 2));
	}

	@Override
	public void dismiss() {
		super.dismiss();

		mAdViewBannerContainer.removeAllViews();
		mAdShowing = false;
	}

//	public void showAd(String adCacheKey) {
//		if (mAdShowing) {
//			return;
//		}
//		if (!AdManager.getInstance().hasAd(adCacheKey)) {
//			return;
//		}
//		mAdCacheKey = adCacheKey;
//		Object ad = AdManager.getInstance().getAd(mAdCacheKey);
//		if (ad != null) {
//			mAdViewBannerContainer.removeAllViews();
//			mAdViewBannerContainer.setVisibility(View.VISIBLE);
//
//			Intent intent = AdDisplay.makeIntent(mAdCacheKey, ad);
//			if (mAdView == null) {
//				mAdView = AllinoneAdView.newAllinoneAdView(LayoutInflater.from(mContext), R.layout.ad_sticker_preview_banner_view, null);
//			}
//			final BaseNativeAdView baseNativeAdView = mAdView.getBaseNativeAdView();
//			if (baseNativeAdView != null) {
//				baseNativeAdView.setDefaultImageResource(R.drawable.default_image);
//			}
//			mAdView.setData(intent);
//			mAdViewBannerContainer.addView(mAdView.getViewAndRemoveParent());
//
//			TranslateAnimation animation = new TranslateAnimation(
//					Animation.RELATIVE_TO_SELF, 0.0f,
//					Animation.RELATIVE_TO_SELF, 0.0f,
//					Animation.RELATIVE_TO_SELF, -1.0f,
//					Animation.RELATIVE_TO_SELF, 0.0f);
////			animation.setStartTime(500);
//			animation.setDuration(500);
//			animation.setInterpolator(new CubicBezierInterpolator(0,1.06,.73,1));
//			mAdViewBannerContainer.startAnimation(animation);
//
//			mAdShowing = true;
//		}
//	}

	public void showMainPagePopGif(View parent, int gravity, int x, int y) {
		if (!this.isShowing()) {
//			showAd(mAdCacheKey);
			this.showAtLocation(parent, gravity, x, y);
		} else {
			this.dismiss();
		}
	}

//	public void setLocal(boolean mLocal, StorePreviewLoader mImageLoader) {
//		mIsLocal = mLocal;
//		this.mImageLoader = mImageLoader;
//	}

	public boolean isLocal() {
		return mIsLocal;
	}

	private class MainPageAdapter extends PagerAdapter {

		private Context mContext;
		private List<IGifBean> mGifIdList;

		public MainPageAdapter(Context context, List<IGifBean> mGifIdList2) {
			this.mContext = context;
			this.mGifIdList = mGifIdList2;
		}

		@Override
		public int getCount() {
			return mGifIdList.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View)object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View convertView = LayoutInflater.from(mContext).inflate(
					R.layout.mainpage_pop_lv_item, null);
			SketchImageView img = convertView
					.findViewById(R.id.mainpage_pop_lv_item_img);
			String url = mGifIdList.get(position).getGifUrl();
			if(mDynamicSize) {
				final ProgressView progressView = (ProgressView) convertView.findViewById(R.id.loading_view);
				final View loadingLayout = convertView.findViewById(R.id.loading_progress);
				loadingLayout.setBackgroundColor(0x55000000);
				int[] dims = mGifIdList.get(position).getDims();
				int width = (int)(defaultSize * (dims[0] * 1.0f / dims[1]));
				if(width > gifMaxWidth) {
					width = gifMaxWidth;
				}
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) loadingLayout.getLayoutParams();
				layoutParams.height = defaultSize;
				layoutParams.width = width;
				layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
				RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) img.getLayoutParams();
				layoutParams1.height = defaultSize;
				layoutParams1.width = width;
				loadingLayout.setVisibility(View.VISIBLE);
				progressView.start();
				img.setScaleType(ImageView.ScaleType.CENTER_CROP);
				img.setDisplayListener(new DisplayListener() {
					@Override
					public void onStarted() {

					}

					@Override
					public void onCompleted(@NonNull Drawable drawable, @NonNull ImageFrom imageFrom, @NonNull ImageAttrs imageAttrs) {
						loadingLayout.setVisibility(View.GONE);
						progressView.stop();
					}

					@Override
					public void onError(@NonNull ErrorCause cause) {

					}

					@Override
					public void onCanceled(@NonNull CancelCause cause) {

					}
				});
				img.getOptions().setDecodeGifImage(true);
				img.displayImage(url);
			} else {
				RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) img.getLayoutParams();
				layoutParams1.height = defaultSize;
				layoutParams1.width = defaultSize;
				img.setScaleType(ImageView.ScaleType.FIT_XY);
				img.setImageResource(R.drawable.ic_default_image);
				if(mLoadAssert && mResources != null) {
					url = StoreOnlineBean.removeQueryString(url);
					String assertPath = url.substring(mRootUrl == null ? 0 : mRootUrl.length() + 1);
					APKAssertImageLoader.with(mResources).load(assertPath).into(img);
				} else {
					ImageLoader.loadImage((Activity) mContext, url, R.drawable.ic_default_image, img);
				}
			}

			container.addView(convertView);
			return convertView;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
	}

	private OnApplyBtnClickListener mOnApplyBtnClickListener;

	public void setOnApplyBtnClickListener(OnApplyBtnClickListener onApplyBtnClickListener) {
		mOnApplyBtnClickListener = onApplyBtnClickListener;
	}

	public interface OnApplyBtnClickListener {
		void onApplyBtnClick(int position);
	}

}
